package taptap

import (
	"batbat-backend/app/model"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/util/grand"
)

/*
获取并解析taptap的游戏评论
*/

// GetReview 获取taptap评论
func GetReview(game *model.Game) ([]*model.GameReview, []*model.User, error) {
	var (
		expectSize = grand.Intn(500) + 501                 // 随机数获取评论数量的期望大小
		idx        = 0                                     // 当前索引位置
		reviews    = make([]*model.GameReview, expectSize) // 评论结果集
		users      = make([]*model.User, expectSize)       // 用户结果集
		err        error                                   // 错误结果
		review     = new(taptapGameReview)                 // 评论列表解析对象
	)
	// 传入第一页url
	review.Data.NextPage = genReviewStartUri(int(game.TaptapId))

	for review.Data.NextPage != "" && idx < expectSize {
		// 向url发起请求
		url := genReviewUrl(review.Data.NextPage)
		review, err = getTaptapGameReview(url)
		if err != nil {
			return nil, nil, gerror.Newf("处理评论发生错误, err=%v", err)
		}
		if !review.Success {
			return nil, nil, gerror.Newf("获取评论列表失败, review=%v", review)
		}

		// 解析当前页的数据
		for _, r := range review.Data.List {
			if r.Moment.ExtendedEntities.Reviews == nil || len(r.Moment.ExtendedEntities.Reviews) == 0 {
				continue
			}
			// 解析用户
			ru := r.Moment.Author.User
			gender := 0
			switch ru.Gender { // 解析用户性别
			case "":
				gender = 0
			case "male":
				gender = 1
			case "female":
				gender = 2
			}
			users[idx] = &model.User{
				UpdateTime:   gtime.Now(),
				Username:     ru.Name,
				Password:     gmd5.MustEncrypt(ru.Name), // 随便选择一个方式来生成密码
				PhoneNumber:  gconv.String(ru.Id),       // 使用phoneNumber作为taptapId
				Avatar:       ru.MediumAvatar,
				Gender:       gender,
				Introduction: ru.Intro,
			}
			// 解析评论
			rr := r.Moment.ExtendedEntities.Reviews[0]
			reviews[idx] = &model.GameReview{
				Gid:        game.Id,
				Uid:        gconv.Uint(ru.Id),
				CreateTime: gtime.New(r.Moment.CreatedTime),
				UpdateTime: gtime.Now(),
				Content:    rr.Contents.Text,
				RawContent: rr.Contents.RawText,
				Score:      rr.Score,
				Like:       uint(rr.Ups),
			}
			idx++
			if idx >= expectSize {
				break
			}
		}
	}
	return reviews[:idx], users[:idx], nil
}

// getTaptapGameReview 根据url访问并解析为taptapGameReview类型
func getTaptapGameReview(url string) (review *taptapGameReview, err error) {
	response, err := g.Client().Get(url)
	if err != nil {
		return nil, gerror.Newf("请求游戏评论列表失败, err=%v", err)
	}
	if response.StatusCode != 200 {
		return nil, gerror.Newf("请求游戏评论列表失败, err=%v, url=%v", err, url)
	}
	body := response.ReadAllString()
	err = gjson.DecodeTo(body, &review)
	if err != nil {
		return nil, gerror.Newf("解析游戏列表失败, err=%v, body=%v", err, body)
	}
	return review, nil
}
